<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="医院名称">
        <el-input v-model="hospset.hosname" />
      </el-form-item>
      <el-form-item label="医院编号">
        <el-input v-model="hospset.hoscode" />
      </el-form-item>
      <el-form-item label="api地址">
        <el-input v-model="hospset.apiUrl" />
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="hospset.contactsName" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="hospset.contactsPhone" />
      </el-form-item>
      <el-form-item>
        <!-- :disabled防止重复提交 -->
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import hospset from "@/api/hospital/hospset";
export default {
  data() {
    return {
      hospset: {},
      saveBtnDisabled: false, // 保存按钮是否禁用,
    };
  },
  created() {
    /**
     * 修改时触发
     * 修改回显跳转:一进入页面,获取路径id值,根据id查询做回显
     * 获取路径中的id值
     */
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id;
      this.fetchDataById(id);
    }
  },
  methods: {
    /**
     * 回显
     */
    fetchDataById(id) {
      hospset.getHospSetById(id).then((response) => {
        this.hospset = response.data.hospitalSet;
      });
    },
    saveOrUpdate() {
      this.saveBtnDisabled = true;
      if (!this.hospset.id) {
        this.saveData();
      } else {
        this.updateData();
      }
    },
    /**
     * 根据id更新记录
     */
    updateData() {
      this.saveBtnDisabled = true;
      hospset
        .updateById(this.hospset)
        .then((response) => {
          return this.$message({
            type: "success",
            message: "修改成功!",
          });
        })
        .then((resposne) => {
          this.$router.push({ path: "/hospset/list"});
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: "保存失败",
          });
        });
    },
    /**
     * 保存
     */
    saveData() {
      hospset
        .saveHospSet(this.hospset)
        // 提示
        .then((response) => {
          return this.$message({
            type: "success",
            message: "保存成功!",
          });
        })
        // 路由跳转
        .then((resposne) => {
          this.$router.push({ path: "/hospset/list" });
        })
        .catch((response) => {
          // console.log(response)
          this.$message({
            type: "error",
            message: "保存失败",
          });
        });
    },
  },
};
</script>